/**
  * SSE 协议适配器
  */
export class SSEAdapter {
  constructor(options) {
    this.options = options;
    this.eventSource = null;
    this.supportsSend = false; // SSE 不支持客户端发送
  }

  connect({ onMessage, onOpen, onClose, onError }) {
    this.eventSource = new EventSource(this.options.url);

    this.eventSource.onopen = onOpen;
    this.eventSource.onerror = (e) => onError(e.error || new Error('SSE 连接异常'));
    this.eventSource.onmessage = (e) => {
      const data = this.options.format === 'json' ? JSON.parse(e.data) : e.data;
      onMessage(data);
    };

    // 自定义事件监听
    if (this.options.events) {
      this.options.events.forEach(event => {
        this.eventSource.addEventListener(event, (e) => {
          onMessage({ type: event, data: e.data });
        });
      });
    }
  }

  disconnect() {
    if (this.eventSource) {
      this.eventSource.close();
      this.eventSource = null;
    }
  }
}